//
//  EmoticonManager.swift
//  EmoticonKeyBoard
//
//  Created by yang on 15/11/21.
//  Copyright © 2015年 yang. All rights reserved.
//

import UIKit

class EmoticonManager: NSObject {
    //单例对象
    static let emoticonManager: EmoticonManager = EmoticonManager()

    lazy var packages = [EmoticonPackage]()
    override init(){
    super.init()
       loadpPackages()
    }
    func loadpPackages(){
        let path = NSBundle.mainBundle().pathForResource("emoticons", ofType: "plist", inDirectory: "Emoticons.bundle")
        let dict = NSDictionary(contentsOfFile: path!)!
        if let array = dict["packages"] as? [[String : AnyObject]]
        {
            for item in array{
                let id = item["id"] as! String
                loadGroupPackage(id)
            }
        }
    
    }
    private func loadGroupPackage(id:String){
        let path = NSBundle.mainBundle().pathForResource("Info", ofType: "plist", inDirectory: "Emoticons.bundle/\(id)")
        let dict = NSDictionary(contentsOfFile: path!)!
        let name = dict["group_name_cn"] as! String
        let array = dict["emoticons"] as! [[String : String]]
        let p = EmoticonPackage(id: id, group_name_cn: name, emoticons: array)
        packages.append(p)
    }
    //提取字符串中的表情字符串
    func textToImageText(str:String,font: UIFont) -> NSAttributedString{
        //正则表达式匹配方案
        let pattern = "\\[.*?\\]"
        //实例化正则表达式
        let regex = try! NSRegularExpression(pattern: pattern, options: [])
        let result = regex.matchesInString(str, options: [], range: NSMakeRange(0, str.characters.count))
        //字符串的属性文本
        let strM = NSMutableAttributedString(string: str)
        //在表情的对象数组中 通过找到的表情字符串 找到对应的表情对象
        var count = result.count - 1
        while count >= 0 {
            //获取每一个表情字符的位置
            let range = result[count].rangeAtIndex(0)
            //截取对应的字符串中的表情字符串
            let subStr = (str as NSString).substringWithRange(range)
            //获取对应的表情模型
            if let emoticon = getEmoticon(subStr){
                // 根据 表情对象中的imagePath找到对应的图片
                let imageText = EmoticonAttachment().emoticonimageText(emoticon,font:font)
                 //替换属性文本
                strM.replaceCharactersInRange(range, withAttributedString: imageText)
            }
            count--
        }
      return strM
    }
    //在表情图片的对象数组中 通过找到的表情字符串 找到对应的表情对象
        func getEmoticon(str:String) -> Emoticon? {
            //遍历所有的表情数组
            for p in EmoticonManager().packages{
                let list = p.emoticonList.filter ({ (emoticon) -> Bool in
                    return emoticon.chs == str
                })
                if let e = list.last {
                    return e
                }
            }
            return nil
        }
}
